#include "widget.h"
#include "util.h"
#include <QDebug>
#include <QPaintEvent>
#include <QPainter>

#include <QtMath>

Widget::Widget(QWidget *parent) : QWidget(parent), frames(60), fIdx(0), imgData(nullptr)
{

    this->setFixedSize(800,600);

    double d = 1000.0 / 60;

    QString pacmanPic = ":/pic/pacman.png";
    hero = new Pacman(0,0,50,50,":/pic/pacman.png");

    hero->face()[Direction::RIGHT] = QPixmap(pacmanPic);
    hero->face()[Direction::LEFT] = QPixmap(pacmanPic).transformed(QTransform().scale(-1,1));

    hero->face()[Direction::UP] = QPixmap(pacmanPic).transformed(QTransform().rotate(-90));
    hero->face()[Direction::DOWN] = QPixmap(pacmanPic).transformed(QTransform().rotate(90));


    QString prefixEnemy(":/pic/enemy%1.webp");
    for(int i=0;i<10;i++){
        auto e = new Enemy(nextRandom(800),nextRandom(600),50,50,prefixEnemy.arg(nextRandom(9)));
        enemies.push_back(e);
    }

    for (int i = 0; i < 1000; i++) {
        auto f = new Food(nextRandom(800),nextRandom(600),10,10,":/pic/bean.png");
        foods.push_back(f);

        f->mf.initialParams.push(nextRandom(30));
        f->mf.initialParams.push(nextRandom(10));
        f->mf.initialParams.push(nextRandom(30));
        f->mf.initialParams.push(nextRandom(10));
        f->mf.initialParams.push(nextRandom(60));

        f->mf.f = [f, d]() {
            static double t = 0;
            double A = f->mf.initialParams[0];
            double w = f->mf.initialParams[1];
            double q = f->mf.initialParams[2];
            double a = f->mf.initialParams[3];
            auto freq = f->mf.initialParams[4];


            f->ry() = f->rOriginY() +A*qCos(2*M_PI*w*freq*t+q)+a;

            f->rx() = f->rOriginX()
                    +nextRandom(30)
                    *qSin(2*M_PI*nextRandom(12)*freq*t
                          +nextRandom(30))
                    +nextRandom(10);

            t += d;
        };
    }

    //60 frames 1 s
    heroTimer.setInterval(d);

    if (g.GifBegin(&writer, "demo2.gif", width(), height(), 2)) { //0.01 unit
        qDebug() << "OK to start gif captured";
    }
    //必须要自己转化下to data原始数据，img的bits()接口数据有问题
    //原始QImage bits() 数据输出颜色不对！！！
    int dataSize = width() * height() * 4;
    imgData = new uint8_t[dataSize];
    auto getRgbData = [this, dataSize](auto img) -> auto
    {
        //zero data array
        memset(imgData, 0, dataSize);

        // 2. 遍历像素
        for (int y = 0; y < img.height(); y++) {
            for (int x = 0; x < img.width(); x++) {
                // 3. 获取像素的 QRgb 值
                QRgb pixel = img.pixel(x, y);

                // RGBA A is last!!!
                // 4. 提取 R, G, B 分量
                int r = qRed(pixel);
                int g = qGreen(pixel);
                int b = qBlue(pixel);

                int idx = y * img.width() + x;
                idx = idx * 4; //RGBA 4 bytes

                imgData[idx] = r;
                imgData[idx + 1] = g;
                imgData[idx + 2] = b;
                imgData[3 + idx] = qAlpha(pixel); //
                                                  //                qDebug() << idx;
                // 5. 打印或处理 RGB
                //                qDebug() << "Pixel at (" << x << "," << y << "): R=" << r << " G=" << g
                //                         << " B=" << b;
            }
        }
        return imgData;
    };

    //OK two!!
    auto getImgData2 = [this, dataSize](auto image) -> auto
    {
        //zero data array
        memset(imgData, 0, dataSize);

        const uchar *bits = image.bits(); // 获取原始数据指针
        int width = image.width();
        int height = image.height();
        int bytesPerLine = image.bytesPerLine(); // 每行字节数

        for (int y = 0; y < height; y++) {
            const QRgb *line = reinterpret_cast<const QRgb *>(bits + y * bytesPerLine);
            for (int x = 0; x < width; x++) {
                QRgb pixel = line[x];
                int r = qRed(pixel);
                int g = qGreen(pixel);
                int b = qBlue(pixel);

                // 处理 RGB 数据...
                int idx = y * image.width() + x;
                idx = idx * 4; //RGBA 4 bytes

                imgData[idx] = r;
                imgData[idx + 1] = g;
                imgData[idx + 2] = b;
                imgData[3 + idx] = qAlpha(pixel); //
            }
        }
        return imgData;
    };

    connect(&heroTimer, &QTimer::timeout, [this, getRgbData, getImgData2]() {
        //        static double angle = 20;
        //        int a = 100;
        //        int x = a*qPow(qCos(qDegreesToRadians(angle)),3) + 300;
        //        int y = a*qPow(qSin(qDegreesToRadians(angle)),3) + 300;

        //        hero->setPos(x,y);

        //        angle += 5;

        for(auto &food:foods){
            food->mf.f();
            //            qDebug() << food->rx() << "," << food->ry();
        }

        update();

        if (frames > fIdx) {
            g.GifWriteFrame(
                &writer,
                //                            grab().toImage().convertToFormat(QImage::Format_ARGB32).bits(),
                //getRgbData(
                //  grab().toImage()), //必须要自己转化下to data原始数据，img的bits()接口数据有问题
                getImgData2(grab().toImage()), //Ok
                //grab().toImage().bits(),//blue ? what's wrong?
                width(),
                height(),
                2);
            fIdx++;
        } else {
            g.GifEnd(&writer);
            if (imgData) {
                delete[] imgData;
                imgData = nullptr;
                qDebug() << "gif grab window over";
            }
        }
    });

    heroTimer.start();



}

Widget::~Widget()
{
}


void Widget::paintEvent(QPaintEvent *e){
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);



    for(auto &f:foods){
        f->draw(p);
    }

    for(auto &e:enemies){
        e->draw(p);
    }

    hero->draw(p);
}

void Widget::keyPressEvent(QKeyEvent *e)
{
    int sd = 20;
    int k = e->key();
    switch (k) {
    case Qt::Key_W:
        hero->setDirection(Direction::UP,sd);
        break;
    case Qt::Key_S:
        hero->setDirection(Direction::DOWN,sd);
        break;
    case Qt::Key_A:
        hero->setDirection(Direction::LEFT,sd);
        break;
    case Qt::Key_D:
        hero->setDirection(Direction::RIGHT,sd);
        break;
    default:
        break;
    }

    update();
}
